import {
  Controller,
  Req,
  Get,
  Post,
  HttpCode,
  Header,
  Param,
  Body,
  BadRequestException,
  ParseIntPipe,
  UsePipes,
  Query,
  DefaultValuePipe,
  ParseBoolPipe,
  UseGuards,
} from '@nestjs/common';
import { Request } from 'express';
// import { CreateCatDto, createCatSchema } from './dto/create-cat.dto';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
import { ForbiddenException } from 'src/forbidden.exception';
import { ZodValidationPipe } from 'src/pipes/zodValidation.pipe';
import { ValidationPipe } from 'src/pipes/validation.pipe';
import { RolesGuard } from 'src/guards/roles.guard';
import { Roles } from 'src/guards/roles.decorator';

@Controller('cats')
// 绑定守卫
@UseGuards(RolesGuard)
export class CatsController {
  constructor(private catsService: CatsService) {}

  @Get()
  async findAll(
    @Req() request: Request,
    // 默认值 DefaultValuePipe
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
    @Query('activeOnly', new DefaultValuePipe('默认值'), ParseBoolPipe)
    activeOnly: boolean,
  ): Promise<Cat[]> {
    // return '此接口查询所有的小猫';
    // throw new BadRequestException('Something bad happened', {
    //   cause: new Error(),
    //   description: 'Some error description',
    // });
    // throw new ForbiddenException();
    return this.catsService.findAll();
  }

  //   @Post()
  //   @HttpCode(200) // 默认情况下响应状态代码始终为 200，POST 请求除外，该代码为 201
  //   @Header('Cache-Control', 'no-store')
  // //   @UsePipes(new ZodValidationPipe(createCatSchema))
  //   creat(@Body() createCatDto: CreateCatDto) {
  //     this.catsService.create(createCatDto);
  //   }
  @Post()
  @HttpCode(200)
  @Roles(['admin', 'xxx', 'xxx2']) // 将 Roles 装饰器元数据附加到 create() 方法，表明只有具有 admin 角色的用户才可以访问此路由
  async create(@Body(new ValidationPipe()) createCatDto: CreateCatDto) {
    this.catsService.create(createCatDto);
  }

  @Get(':id')
  // ParseIntPipe 要求接受的参数是数字
  findOne(@Param('id', ParseIntPipe) id: number) {
    console.log(typeof id === 'number'); // true
    return this.catsService.findOne(id);
  }
}
